<template>
	<coreshop-page title="分享" mode="left">
		<view class="layout-invite-box">
			<image class="share-img" :src="url"></image>

			<view class="btn" @click="handlesavePoster">保存到本地</view>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { ref } from 'vue';
	import type { ShopConfigStoreType } from '@/core/models';
	import { useShopConfigStore } from '@/core/store';
	import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import { shareUrl } from '@/core/consts';
	import { handleShowToast } from '@/core/utils';

	interface QueryParams {
		poster : string;
	}

	/** 获取项目配置 */
	const shopConfigStore : ShopConfigStoreType = useShopConfigStore();

	const url = ref('');

	onLoad((query : QueryParams) => {
		url.value = decodeURIComponent(query.poster);
	})

	/** 保存到本地 */
	const handlesavePoster = () => {
		// #ifdef APP-PLUS || APP-PLUS-NVUE
		uni.downloadFile({
			url: url.value,
			success(res : any) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success() {
						handleShowToast('保存成功', 'success');
					},
					fail() {
						handleShowToast('图片保存失败', 'error');
					}
				});
			},
			fail() {
				handleShowToast('下载失败', 'error');
			}
		})
		// #endif

		// #ifdef MP
		uni.authorize({
			scope: 'scope.writePhotosAlbum',
			success() {
				// 先下载到本地
				uni.downloadFile({
					url: url.value,
					success(res : any) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success() {
								handleShowToast('保存成功', 'success');
							},
							fail() {
								handleShowToast('图片保存失败', 'error');
							}
						});
					},
					fail() {
						handleShowToast('下载失败', 'error');
					}
				})
			}
		})
		// #endif
	}

	onShareAppMessage(() => {
		return {
			title: shopConfigStore.config.shareTitle,
			imageUrl: shopConfigStore.config.shareImage,
			path: shareUrl
		}
	});

	onShareTimeline(() => {
		return {
			title: shopConfigStore.config.shareTitle,
			imageUrl: shopConfigStore.config.shareImage,
			path: shareUrl
		}
	})
</script>
<style lang="scss" scoped>
	@import './qrCode.scss';
</style>